<template>
  <div>
    <el-tabs v-model="activeTab">
      <el-tab-pane
        v-for="(value, key) in TAB_PROCESS_CONFIG_ENUM"
        :key="key"
        :label="value"
        :name="key"
      >
        <el-form ref="refForm" :model="formData" label-position="top">
          <!-- <el-collapse v-model="activeName" accordion>
            <el-collapse-item name="1">
              <template slot="title">
                <span class="el_title">基本信息<i class="header-icon el-icon-info"/></span>
              </template> -->

          <el-form-item v-show="activeTab === 'BASE'" label="流程Key">
            <span class="b">{{ modelData.key }}</span>
          </el-form-item>

          <el-form-item v-show="activeTab === 'BASE'" label="流程名称">
            {{ modelData.name }}
          </el-form-item>

          <el-form-item v-show="activeTab === 'BASE'" label="流程描述">
            {{ modelData.description }}
          </el-form-item>

          <el-form-item v-show="activeTab === 'BASE'" label="流程分类">
            {{ modelData.category }}
          </el-form-item>

          <!-- </el-collapse-item> -->

          <!-- </el-collapse> -->

          <!-- <el-collapse v-model="activeName" accordion> -->
          <!-- <el-collapse-item name="2"> -->
          <!-- <template slot="title">
            <span class="el_title">流程配置<i class="header-icon el-icon-info"/></span>
          </template> -->

          <el-form-item
            v-show="activeTab === 'BASE'"
            label="关联模型"
            prop="modelId"
            :rules="[
              { required: true, message: '请选择关联模型', trigger: 'change' },
            ]"
          >
            <!--        <el-select-->
            <!--          :disabled="!processCanEdit"-->
            <!--          v-model="formData.modelId"-->
            <!--          style="width: 100%"-->
            <!--          filterable-->
            <!--        >-->
            <!--          <el-option-->
            <!--            v-for="item in modelList"-->
            <!--            :key="item.id"-->
            <!--            :value="item.id"-->
            <!--            :label="`${item.name}(${item.code})`"/>-->
            <!--        </el-select>-->
            <tree-select
              :disabled="!processCanEdit"
              v-model="formData.modelId"
              filterable
              :fieldMap="{
                value: 'id',
                label: 'name',
                disabled: 'disabled',
              }"
              :filterNodeMethod="filterNodeMethod"
              :treeData="modelList"
            />
            <!-- <el-input
              v-else
              disabled
              v-model="formData.modelName"
              style="width: 350px"
            ></el-input> -->
          </el-form-item>
          <!-- <el-form-item
            label="编辑表单"
            :rules="[
              { required: true, message: '请选择编辑表单', trigger: 'change' },
            ]"
          >
            <el-select
              v-if="isNew"
              v-model="formData.modelId"
              style="width: 350px"
              filterable
              remote
              :remote-method="loadModelList"
              :loading="modelLoading"
            >
              <el-option v-for="item in modelList" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select>
            <el-input
              v-else
              disabled
              v-model="formData.modelName"
              style="width: 350px"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="查看表单"
            :rules="[
              { required: true, message: '请选择查看表单', trigger: 'change' },
            ]"
          >
            <el-select
              v-if="isNew"
              v-model="formData.modelId"
              style="width: 350px"
              filterable
              remote
              :remote-method="loadModelList"
              :loading="modelLoading"
            >
              <el-option v-for="item in modelList" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select>
            <el-input
              v-else
              disabled
              v-model="formData.modelName"
              style="width: 350px"
            ></el-input>
          </el-form-item> -->

          <!-- </el-collapse-item> -->

          <!-- </el-collapse> -->
          <!--表单-->
          <el-form-item
            v-show="activeTab === 'FORM'"
            label="待办表单"
          ></el-form-item>
          <el-form-item v-if="activeTab === 'FORM'" prop="formKey">
            <template slot="label">
              <span class="dib mr10">PC</span>
              <el-button type="text" @click="preview('PC', formData.formKey)">
                <i class="el-icon-view"></i
                ></el-button>
            </template>
            <tree-select
              :disabled="!processCanEdit"
              v-model="formData.formKey"
              style="width: 100%"
              clearable
              filterable
              :fieldMap="{
                value: 'key',
                label: 'name',
                disabled: 'disabled',
              }"
              :filterNodeMethod="filterNodeMethod"
              :treeData="pageList"
            />
          </el-form-item>

          <el-form-item
            v-if="activeTab === 'FORM'"
            label="APP"
            prop="appFormKey"
          >
            <tree-select
              :disabled="!processCanEdit"
              v-model="formData.appFormKey"
              clearable
              style="width: 100%"
              filterable
              :fieldMap="{
                value: 'key',
                label: 'name',
                disabled: 'disabled',
              }"
              :filterNodeMethod="filterNodeMethod"
              :treeData="appPageList"
            />
          </el-form-item>
          <el-form-item
            v-show="activeTab === 'FORM'"
            label="查看表单"
          ></el-form-item>
          <el-form-item v-if="activeTab === 'FORM'" prop="formView">
            <template slot="label">
              <span class="dib mr10">PC</span>
              <el-button
                type="text"
                @click="preview('PC', formData.formView)"
              ><i class="el-icon-view"></i
              ></el-button>
            </template>
            <tree-select
              v-model="formData.formView"
              :disabled="!processCanEdit"
              clearable
              style="width: 100%"
              filterable
              :fieldMap="{
                value: 'key',
                label: 'name',
                disabled: 'disabled',
              }"
              :filterNodeMethod="filterNodeMethod"
              :treeData="pageList"
            />
          </el-form-item>

          <el-form-item
            v-if="activeTab === 'FORM'"
            label="APP"
            prop="appFormView"
          >
            <tree-select
              :disabled="!processCanEdit"
              v-model="formData.appFormView"
              style="width: 100%"
              clearable
              filterable
              :fieldMap="{
                value: 'key',
                label: 'name',
                disabled: 'disabled',
              }"
              :filterNodeMethod="filterNodeMethod"
              :treeData="appPageList"
            />
          </el-form-item>
          <!--通知-->
          <el-form-item
            v-if="activeTab === 'NOTICE'"
            label="待办通知"
            placeholder="请选择"
            prop="noticeTodoKey"
          >
            <el-select
              style="width: 100%"
              clearable
              v-model="formData.noticeTodoKey"
              filterable
            >
              <el-option
                v-for="item in msgTemplateList"
                :key="item.code"
                :value="item.code"
                :label="item.code"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            v-if="activeTab === 'NOTICE'"
            label="流程结束通知"
            prop="noticeEndKey"
          >
            <el-select
              clearable
              placeholder="请选择"
              style="width: 100%"
              v-model="formData.noticeEndKey"
              filterable
            >
              <el-option
                v-for="item in msgTemplateList"
                :key="item.code"
                :value="item.code"
                :label="item.code"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item
            label="知会表单"
            prop="formNotice"
          >
            <el-select
              style="width: 100%"
              v-model="formData.formNotice"
              filterable
            >
              <el-option v-for="item in pageList" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select>
          </el-form-item> -->
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import mixinPanel from '../mixins/mixinPanel'
// import lodash from 'lodash'
import { getFields, setFields } from '../utils/util'
import { filterNodeMethod } from '@/utils/treeSelectFormat'

import { TAB_PROCESS_CONFIG_ENUM } from '@/utils/enum'

import { getHmmodelfolderListTree } from '@/apis/paas/HmModelFolderController.js'
import { getHmpagefolderListTree } from '@/apis/paas/HmPageFolderController.js'
import { getMsgTemplateconfigPagelist } from '@/apis/paas/MsgTemplateConfigController.js'
import { getHmpageInfoKey } from '@/apis/paas/HmPageController.js'
import lodash from 'lodash'
import DesignPreview from '@/components/DesignPreview/index.js'
const defaultTab = Object.keys(TAB_PROCESS_CONFIG_ENUM)[0]
export default {
  name: 'BpmnProcess',
  mixins: [mixinPanel],
  data () {
    // this.loadModelList = lodash.debounce(this.loadModelList, 300)
    return {
      activeTab: defaultTab,
      // activeName: '2',
      TAB_PROCESS_CONFIG_ENUM,
      filterNodeMethod,
      formData: {},
      modelList: [],
      modelListFlat: [],
      msgTemplateList: [],
      // modelLoading: false,
      pageList: [],
      appPageList: []
    }
  },

  computed: {
    ...mapGetters(['processCanEdit'])
  },

  created () {
    this.init()
  },

  watch: {
    // 'formData.processCategory': function (val) {
    //   if (val === '') {
    //     val = null
    //   }
    //   this.element.businessObject.$parent.targetNamespace = val
    // },

    // 'formData.candidateStarterUsers': function (val) {
    //   this.updateProperty('candidateStarterUsers', val, true)
    // },
    // 'formData.candidateStarterGroups': function (val) {
    //   this.updateProperty('candidateStarterGroups', val, true)
    // },

    'formData.modelId': function (val) {
      let modelKey = ''
      const modelId = val ? String(val) : ''
      if (val) {
        const model = this.modelListFlat.find(item => item.id === val)
        modelKey = model?.code || modelId
      }
      setFields(this.modeler, this.element, {
        model: modelKey
      })

      this.loadPageList('ALL')
      this.loadPageList('APP')
    },
    'formData.formKey': function (val) {
      setFields(this.modeler, this.element, {
        formKey: val ? String(val) : ''
      })
    },
    'formData.formView': function (val) {
      setFields(this.modeler, this.element, {
        formView: val ? String(val) : ''
      })
    },
    'formData.appFormKey': function (val) {
      setFields(this.modeler, this.element, {
        appFormKey: val ? String(val) : ''
      })
    },
    'formData.appFormView': function (val) {
      setFields(this.modeler, this.element, {
        appFormView: val ? String(val) : ''
      })
    },
    'formData.noticeTodoKey': function (val) {
      setFields(this.modeler, this.element, {
        noticeTodoKey: val ? String(val) : ''
      })
    },
    'formData.noticeEndKey': function (val) {
      setFields(this.modeler, this.element, {
        noticeEndKey: val ? String(val) : ''
      })
    }

    // 'formData.formNotice': function (val) {
    //   setFields(this.modeler, this.element, {
    //     formNotice: val ? String(val) : ''
    //   })
    // }
  },

  methods: {
    async init () {
      const fields = getFields(this.element.businessObject)

      const {
        model,
        formKey,
        formView,
        appFormKey,
        appFormView,
        noticeTodoKey,
        noticeEndKey
      // formNotice
      } = fields

      this.$set(this.formData, 'formKey', formKey)
      this.$set(this.formData, 'formView', formView)
      this.$set(this.formData, 'appFormKey', appFormKey)
      this.$set(this.formData, 'appFormView', appFormView)
      this.$set(this.formData, 'noticeTodoKey', noticeTodoKey)
      this.$set(this.formData, 'noticeEndKey', noticeEndKey)

      // 关联模型直接全部加载
      this.loadMsgTemplate()
      const res = await this.$parent.modelPromise
      this.modelList = res.tree
      this.modelListFlat = res.list
      const modelId = this.getModelIdByCode(/^\d+$/.test(model) ? this.modelData.modelCode : model)
      this.$set(this.formData, 'modelId', modelId ? Number(modelId) : undefined)
    },

    getModelIdByCode (code) {
      const model = this.modelListFlat.find(item => item.code === code)
      return model?.id
    },
    // 表单预览
    async preview (type, pageKey) {
      if (!pageKey) {
        this.$message.info('请选择表单')
        return
      }
      const { json, name } = await getHmpageInfoKey({
        key: pageKey,
        includeJson: true
      })
      try {
        if (json) {
          const { FormData, formList } = JSON.parse(json)
          DesignPreview.openDrawer({
            hmpageInfo: FormData,
            formList,
            title: name
          })
        } else {
          this.$message.info('表单未保存')
        }
      } catch (error) {
        console.log(error)
      }
    },
    loadPageList (type = 'ALL') {
      const { modelId } = this.formData
      if (!modelId) {
        return
      }
      getHmpagefolderListTree({
        modelId,
        type,
        // type: 'FORM',
        filterNonJson: true
      }).then((res) => {
        res.forEach((node) => {
          node.type = 'folder'
        })
        if (type === 'ALL') {
          this.pageList = this.createPageTreeNode(res)
        } else if (type === 'APP') {
          this.appPageList = this.createPageTreeNode(res)
        }

        // this.pageList = res.map(item => {
        //   item.__formKey__ = `${item.key}.form`
        //   return item
        // })
      })
    },

    async loadModelList () {
      const res = await getHmmodelfolderListTree()
      res.forEach((node) => {
        node.type = 'folder'
      })
      // 支持流程模型的model
      this.modelList = this.createModelTreeNode(res || [])
    },
    loadMsgTemplate () {
      getMsgTemplateconfigPagelist({ pageSize: 100000 }).then((res) => {
        this.msgTemplateList = res.data
      })
    },
    createModelTreeNode (tree) {
      return lodash.cloneDeep(tree).map((node) => {
        node.disabled = node.type === 'folder'
        if (node.modelResults) {
          node.id = 'folder' + node.id
          node.children = node.modelResults.filter(
            (item) => item.supportProcess
          )
          node.children.forEach((item) => {
            item._id = item.id
            item.name = `${item.name}(${item.code})`
          })
        }
        return node
      })
    },
    createPageTreeNode (tree) {
      return lodash.cloneDeep(tree).map((node) => {
        node.disabled = node.type === 'folder'
        if (node.pageResults) {
          node.id = 'folder' + node.id
          node.children = node.pageResults || []
          node.children.forEach((item) => {
            item.__formKey__ = `${item.key}.form`
            item.name = `${item.name}（${item.key}）`
          })
        }
        return node
      })
    }
  }
}
</script>

<style lang="scss">
</style>
